#!/usr/bin/python3

# Inkbunny Status Reporter 0.1.0
# Copyright 2025 JustLurking

# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.

# About
# This program will connect to Inkbunny using the session cookie in the
# PHPSESSID environment variable and take an action based on the arguments
# provided.
#
# With no arguments the status will be reported the user on stdout and
# the program will exit with status 0.
#
# A single argument will be taken as a key to watch.  The value of just
# that key will be reported on stdout.  The program will exit with status
# 1 if the key is 0, "0" or "no"; any other value will cause it to exit
# with status 0
#
# Further arguments will be taken as a command to run in the case where
# the key being inspected is not 0, "0" or "no".  The program exits with
# status 0 if the key is 0, "0" or "no" the opposite of the previous mode
# otherwise the command given by the user replaces the process.

# Changelog
# 2025-01-03 JustLurking: Initial Release.

import argparse
import json
import logging
import os
import requests
import sys

# Program identity.
program_file  = "ib-status"
program_name  = "Inkbunny Status Reporter"
version       = "0.1.0"
bug_reports   = "https://Inkbunny.net/JustLurking/"
homepage      = "https://inkbunny.net/submissionsviewall.php?mode=pool&pool_id=98446"

# Main Program starts here.

# Configure logging.
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
log.setLevel(logging.INFO)

# Handle arguments.
arg_parser = argparse.ArgumentParser(
    prog = program_file,
    description = "".join((
        "Fetches user and site status from the Inkbunny.net website and acts"
        " upon them in some way."
    )),
    epilog = "".join((
        "The SESSION may be passed using the PHPSESSID environment variable."
        " this may be useful if you wish to pass the same value to multiple"
        " programs, or if you wish to set the value in your shell's profile.\n"
        "\n",
        "If you wish to run a command that uses arguments also recognised by",
        " "+program_file+" pass a single -- argument before the command to",
        " signal that any further arguments should not be processed.\n",
        "\n",
        "Report bugs to: "+bug_reports+"\n",
        program_name + " home page: <"+homepage+"\n"
    )),
    formatter_class = argparse.RawDescriptionHelpFormatter
)
arg_parser.add_argument(
    "-s",
    "--session",
    nargs = 1,
    help = "the session id to send with requests"
)
arg_parser.add_argument(
    "-V",
    "--version",
    action = "store_true"
)
arg_parser.add_argument(
    "check",
    nargs = '?',
    help = "the key to check for a non-zero value"
)
arg_parser.add_argument(
    "command",
    nargs = '*',
    help = "the command to run if the check passes"
)

args = arg_parser.parse_args()

if args.version:
    print(
        " ".join((program_name, version)),
        "Copyright (C) 2025 JustLurking<https://inkbunny.net/JustLurking>",
        "License GPLv3+: GNU GPL version 3 or later "+
            "<https://gnu.org/licenses/gpl.html>",
        "",
        "This is free software: you are free to change and redistribute it.",
        "There is NO WARRANTY, to the extent permitted by law.",
        sep="\n"
    )
    exit(0)

# Set the Session Cookie from the environment.
cookie = args.session

if cookie is None:
    cookie = os.getenv('PHPSESSID')

if cookie is None:
    log.error("Please use the -s argument or set the PHPSESSID environment variable to set the session id.")
    exit(1)

cookies = requests.cookies.RequestsCookieJar()
cookies.set('PHPSESSID', cookie, domain='inkbunny.net', path='/')

# Get the site status for the signed in user.
resp = requests.get("https://inkbunny.net/check_site_status_process.php", cookies=cookies)
resp.raise_for_status()
status = json.loads(resp.text.splitlines()[1])

# If the user provided no further arguments just report all the values we
# parsed.
if args.check is None:
    for (k, v) in status.items():
        print(k+":", v);
    exit(0)

# Otherwise the first argument is the specific key to check.
if args.check not in status:
    log.error("Unknown key: %s", args.check)
    log.info("Known keys are: %s", ', '.join(status.keys()))
    exit(100);

# The check passes if the key has a non-zero non-no value.
check_successful = status[args.check] not in ('no', '0', 0)
print(status[args.check])

# If that's the last argument just return 0 (success) or 1 (failure) to signal
# the result of the check to our parent.
if args.command != []:
    exit(0 if check_successful else 1)

# If we have more than one argument either return 0 (success) if the check
# didn't pass or exec the remaining arguments if the check passed.
if not check_successful:
    exit(0)
os.execlp(args.command[0], *args.command)

# We can only get here if the exec failed.
exit(101);
